﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Roton2.MemoryEmulation
{
    /// <summary>
    /// Collection of byte arrays, each with a unique index. The .net framework handles garbage collection.
    /// </summary>
    public class Heap
    {
        int allocationCounter;
        Dictionary<int, byte[]> heap;
        HashSet<int> heapHashSet;

        /// <summary>
        /// Allocate an empty heap.
        /// </summary>
        public Heap()
        {
            allocationCounter = int.MinValue;
            heap = new Dictionary<int, byte[]>();
            heapHashSet = new HashSet<int>();
        }

        /// <summary>
        /// Allocate a byte array within the heap. Returns a handle which can be used to release its resources.
        /// </summary>
        public int Allocate(byte[] data)
        {
            while (!heapHashSet.Contains(allocationCounter))
                allocationCounter++;
            heapHashSet.Add(allocationCounter);
            heap.Add(allocationCounter, data);
            
            return allocationCounter;
        }

        /// <summary>
        /// Free resources used by a byte array in the heap. Requires a handle provided by Allocate.
        /// </summary>
        public void Free(int handle)
        {
            if (heapHashSet.Contains(handle))
            {
                heapHashSet.Remove(handle);
                heap.Remove(handle);
            }
        }
    }
}
